<?php


namespace App\Http\Controllers\Api;


use App\Dengje\Utils\Settings;
use App\Http\Controllers\Api\Repositories\PostsRepositores;
use App\Http\Controllers\Api\Repositories\WxUserRepositores;
use App\Models\Posts\WxCollect;
use App\Models\Posts\WxLike;
use App\Models\Posts\WxPost;
use App\Models\Posts\WxUserCircle;
use App\Models\WxAuthentication;
use App\Models\WxCircle;
use App\Models\WxCommentLike;
use App\Models\WxExceptional;
use App\Models\WxOrder;
use App\Models\WxPlate;
use App\Models\WxUser;
use App\Models\WxNotice as NoticeModel;
use App\Models\WxUserFinancial;
use App\Models\WxUserFollow;
use App\Models\WxUserPlate;
use App\Models\WxUserWithdrawal;
use Illuminate\Http\Request;
use JiaweiXS\WeApp\WeApp;
use App\Lib\wxBizDataCrypt\WxBizDataCrypt;
use App\Lib\JwtAuth;


class UserController extends BaseController
{
    /**
     * @param Request $request
     * @param code
     * @param encryptedData
     * @param iv
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function login(Request $request)
    {
        $code = $request->code;
        $encryptedData = $request->encryptedData;
        $iv = $request->iv;
        $userinfo = $request->userInfo;
        //例如，在laravel,文件缓存路径为'../storage/cache/'
        $weapp = new WeApp(Settings::get('app_id'), Settings::get('app_secret'), '../storage/cache/');
        //code 换取 session_key
        $sessionKey = $weapp->getSessionKey($code);
        $sessionKey = json_decode($sessionKey, true);
        $pc = new WXBizDataCrypt(Settings::get('app_id'), $sessionKey['session_key']);
        $errCode = $pc->decryptData($encryptedData, $iv, $data);

        if ($errCode == 0) {
            $data = json_decode($data, true);
            $data['nickName'] = $userinfo['nickName'];
            $data['avatarUrl'] = $userinfo['avatarUrl'];
            $data['province'] = $userinfo['province'];
            $data['country'] = $userinfo['country'];
            $data['gender'] = $data['gender'];
            $data['city'] = $data['city'];
            $wxUserModel = new WxUser();
            $wxUserModel->registerUser($data);
            $uid = $wxUserModel->where('weixin_openid', $data['openId'])->first('id');
            // 生成token
            return $this->success(['token' => JwtAuth::getToken('uid', $uid['id'])]);
        } else {
            return $this->fail(503001);
        }


    }

    /**
     * 获取用户信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function userInfo(Request $request)
    {
        $uid = $request->uid;
        $info = (new WxUserRepositores())->info($uid);
        return $this->success($info);
    }

    /**
     * 根据用户id获取基本用户信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function userInfoByUserId(Request $request)
    {
        $user_id = $request->user_id;
        $token = $request->header('token');
        $uid = 0;
        if ($token) {
            $uid = JwtAuth::getUserId($token, 'uid');
        }
        $data = WxUser::where('id', $user_id)->first(['user_name', 'user_avatar', 'user_introduce', 'user_background_maps', 'is_authentication', 'is_member', 'is_official'])->toArray();

        $data['followTotal'] = WxUserFollow::where('user_id', $user_id)->count();

        $data['fansTotal'] = WxUserFollow::where('user_follow_id', $user_id)->count();
        $count1 = WxLike::where('posts_user_id', $user_id)->count();
        $count2 = WxCommentLike::where('comment_user_id', $user_id)->count();
        $data['likeTotal'] = $count1 + $count2;
        $data['isFollow'] = WxUserFollow::where('user_id', $uid)->where('user_follow_id', $user_id)->exists();
        return $this->success($data);
    }

    /**
     * 通过用户id获取用户发表的帖子
     * @param Request $request
     * @return mixed
     */
    public function postsByUserId(Request $request)
    {
        $user_id = $request->user_id;
        $limit = $request->input('limit', 6);
        $token = $request->header('token');
        $uid = 0;
        if ($token) {
            $uid = JwtAuth::getUserId($token, 'uid');
        }
        $data = (new WxPost())
            ->where('is_examine', 1)
            ->whereIn('posts_state', [0, 2])
            ->where('user_id', $user_id)
            ->orderBy('id', 'desc')
            ->paginate($limit);

        $data = PostsRepositores::postsParame($data, $uid);

        return $this->success($data);
    }


    /**
     * 更新用户资料
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function updateInfo(Request $request)
    {
        $uid = $request->uid;
        $data = $request->all();
        return $this->success(WxUserRepositores::update($uid, $data));
    }

    /**
     * 我的帖子列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getMyPosts(Request $request)
    {

        $uid = $request->uid;

        $limit = $request->input('limit', 6);
        $type = $request->type;
        return $this->success(PostsRepositores::myPosts($uid, $limit, $type));
    }


    /**
     * 用户认证
     */
    public function authentication(Request $request)
    {
        $uid = $request->uid;
        $name = $request->name;
        $contact_information = $request->contact_information;
        $introduce = $request->introduce;
        $identity_picture = $request->identity_picture;
        $authenticationState = (new WxAuthentication())->where('user_id', $uid)->value('authentication_state');
        $authId = (new WxAuthentication())->where('user_id', $uid)->value('id');
        // 已经审核通过和驳回
        if ($authenticationState == 1 || $authenticationState == 2) {
            $model = (new WxAuthentication())->find($authId);
            $model->name = $name;
            $model->contact_information = $contact_information;
            $model->introduce = $introduce;
            $model->identity_picture = $identity_picture;
            $model->authentication_state = 0;
            $model->user_id = $uid;
            $model->save();
        }

        // 首次提交
        if (!$authenticationState) {
            $model = new WxAuthentication();
            $model->name = $name;
            $model->contact_information = $contact_information;
            $model->introduce = $introduce;
            $model->identity_picture = $identity_picture;
            $model->user_id = $uid;
            $model->save();
        }

        return $this->success();


    }

    /**
     * 我创建的圈子列表
     */
    public function myCircle(Request $request)
    {
        $uid = $request->uid;
        $data = WxCircle::where('user_id', $uid)->get();
        $data->map(function ($v) {
            $v->post_count = WxPost::where('circle_id', $v->id)->count();
            $v->user_circle_count = WxUserCircle::where('circle_id', $v->id)->count();
        });
        return $this->success($data);
    }

    /**
     * 获取我的认证信息
     */
    public function getAuthentication(Request $request)
    {
        $uid = $request->uid;
        $model = new WxAuthentication();
        $data = $model->where('user_id', $uid)->first();
        return $this->success($data);
    }

    /**
     * 个人中心 我的帖子，收藏，喜欢，打赏的文章数量
     * @param Request $request
     */
    public function totalPost(Request $request)
    {
        $uid = $request->uid;
        $query = WxPost::where('user_id', $uid)->whereIn('posts_state', [0, 2]);
        if (Settings::get('is_user_center_show_posts') == 1) {
            $query->where('is_examine', 1);
        }
        $data['myTotal'] = $query->count();
        $postsIds = WxLike::where('user_id', $uid)->pluck('posts_id');
        $data['likeTotal'] = WxPost::where('is_examine', 1)->where('posts_state', 0)->whereIn('id', $postsIds)->count();
        $postsIds = WxCollect::where('user_id', $uid)->pluck('posts_id');
        $data['collecTotal'] = WxPost::where('is_examine', 1)->where('posts_state', 0)->whereIn('id', $postsIds)->count();
        $postsIds = WxExceptional::where('user_id', $uid)->pluck('posts_id');
        $data['exceptionalTotal'] = WxPost::where('is_examine', 1)->where('posts_state', 0)->whereIn('id', $postsIds)->count();
        return $this->success($data);
    }

    /**
     * 我关注的用户列表
     * @param Request $request
     */
    public function myFollowUsers(Request $request)
    {
        $uid = $request->uid;
        $user_id = $request->user_id;
        if ($user_id > 0) {
            $data = WxUserFollow::with('followUser')->where('user_id', $user_id)
                ->orderBy('id', 'desc')
                ->simplePaginate(10);
            $data->map(function ($v) use ($user_id) {
                $v->is_together_follow = WxUserFollow::where('user_id', $v->user_follow_id)
                    ->where('user_follow_id', $user_id)->exists();// 是否相互关注
                $v->user = $v->followUser;

            });
            return $this->success($data);
        } else {
            $data = WxUserFollow::with('followUser')->where('user_id', $uid)
                ->orderBy('id', 'desc')
                ->simplePaginate(10);
            $data->map(function ($v) use ($uid) {
                $v->is_together_follow = WxUserFollow::where('user_id', $v->user_follow_id)
                    ->where('user_follow_id', $uid)->exists();// 是否相互关注
                $v->user = $v->followUser;

            });
            return $this->success($data);
        }

    }


    /**
     * 我的粉丝用户列表
     * @param Request $request
     */
    public function myFansUsers(Request $request)
    {
        $uid = $request->uid;
        $user_id = $request->user_id;
        if ($user_id > 0) {
            $data = WxUserFollow::with('user')->where('user_follow_id', $user_id)
                ->orderBy('id', 'desc')
                ->simplePaginate(15);
            $data->map(function ($v) use ($user_id) {
                $v->is_together_follow = WxUserFollow::where('user_id', $user_id)
                    ->where('user_follow_id', $v->user_id)->exists();// 是否相互关注

            });

            return $this->success($data);
        } else {
            $data = WxUserFollow::with('user')->where('user_follow_id', $uid)
                ->orderBy('id', 'desc')
                ->simplePaginate(15);
            $data->map(function ($v) use ($uid) {
                $v->is_together_follow = WxUserFollow::where('user_id', $uid)
                    ->where('user_follow_id', $v->user_id)->exists();// 是否相互关注

            });

            return $this->success($data);
        }

    }

    /**
     * 添加用户标签
     * @param Request $request
     */
    public function addUserPlate(Request $request)
    {
        $plateId = $request->plate_id;
        $uid = $request->uid;
        if ((new WxUserPlate())->where('user_id', $uid)->
        where('plate_id', $plateId)->exists()) {
            return $this->success([], 421001);
        }
//        $sort = $request->input('sort',100);
        $sort = (new WxUserPlate())->where('user_id', $uid)->where('plate_id', $plateId)->orderBy('sort', 'desc')->value('sort');
        // 排序
        if (empty($sort)) {
            $sort = 0;
        } else {
            $sort += $sort;
        }
        $UserPlate = new WxUserPlate();
        $UserPlate->plate_id = $plateId;
        $UserPlate->user_id = $uid;
        $UserPlate->sort = $sort;
        $UserPlate->save();
        return $this->success();
    }

    /**
     * 删除用户标签
     * @param Request $request
     */
    public function deleteUserPlate(Request $request)
    {
        $id = $request->id;
        $uid = $request->uid;
        (new WxUserPlate())->where('user_id', $uid)
            ->where('id', $id)->delete();
        return $this->success();
    }

    /**
     * 用户标签列表
     * @param Request $request
     */
    public function userPlate(Request $request)
    {

        $token = $request->header('token');
        $uid = 0;
        if ($token) {
            $uid = JwtAuth::getUserId($token, 'uid');
        }
        if ($uid == 0) {
            $data = [];
        } else {
            $data = (new WxUserPlate())->where('user_id', $uid)->orderBy('sort', 'asc')->get();
            $data->map(function ($item) {
                $item->plate_name = WxPlate::where('id', $item->plate_id)->value('plate_name');
            });
        }

        return $this->success($data);
    }

    /**
     * 我的订单列表
     */
    public function myOrder(Request $request, $limit = 8)
    {
        $uid = $request->uid;

        $data = WxOrder::where('user_id', $uid)
            ->where('order_state', 1)
            ->orderBy('id', 'desc')
            ->simplePaginate($limit);

        $data->map(function ($v) {
            $v->type_content = WxUserRepositores::orderType($v->order_type);
            $parame = unserialize($v->parame);
            $v->posts_id = $parame['postsId'];
        });

        return $this->success($data);
    }

    /**
     * 我的收益
     */
    public function myFinancial(Request $request)
    {
        $uid = $request->uid;

        $data = WxUserFinancial::where('user_id', $uid)
            ->first();

        $data->earnings_yesterday = WxExceptional::where('posts_user_id', $data->user_id)
            ->where('created_at', 'like', '%' . date("Y-m-d", strtotime("-1 day")) . '%')
            ->sum('exceptional_price');

        return $this->success($data);
    }

    /**
     * 发起提现
     */
    public function initiateWithdrawal(Request $request)
    {
        $uid = $request->uid;
        $price = $request->price;
        $bank_name = $request->bank_name;
        $bank_card = $request->bank_card;

        $wd = WxUserFinancial::where('user_id', $uid)->first();
        $balance = $wd['balance'] - $price;
        $withdrawalPrice = $wd['withdrawal_price'] + $price;
        WxUserFinancial::where('user_id', $uid)
            ->update(['bank_name' => $bank_name, 'bank_card' => $bank_card, 'balance' => $balance, 'withdrawal_price' => $withdrawalPrice]);

        $userWithdrawalModel = new WxUserWithdrawal();
        $userWithdrawalModel->user_id = $uid;
        $userWithdrawalModel->price = $price;
        $userWithdrawalModel->state = 0;
        $userWithdrawalModel->save();

        return $this->success($userWithdrawalModel);
    }

    /**
     * 我的提现记录
     */
    public function myUserWithdrawal(Request $request)
    {
        $uid = $request->uid;

        $data = WxUserWithdrawal::where('user_id', $uid)
            ->orderBy('id', 'desc')
            ->get();

        $data->map(function ($v) {
            $v->status_value = WxUserRepositores::withdrawalType($v->state);
        });

        return $this->success($data);
    }

    /**
     * 免费领会员（限时推广）
     */
    public function freeGetVip(Request $request)
    {
        $uid = $request->uid;

        $data = WxUser::where('id', $uid)
            ->update(['is_member' => 1]);

        $noticeModel = new NoticeModel;
        $noticeModel->user_id = $uid;
        $noticeModel->title = '限时活动领取大会员';
        $noticeModel->content = '您成功参与分享领大会员活动，领取成功已为您开通轻航大会员。';
        $noticeModel->is_read = 0;
        $noticeModel->notice_type = 1;
        $noticeModel->save();

        return $this->success($noticeModel);
    }

    /**
     * 我的收益记录
     */
    public function myUserExceptional(Request $request)
    {
        $uid = $request->uid;

        $data = WxExceptional::where('posts_user_id', $uid)
            ->orderBy('id', 'desc')
            ->get();

        $data->map(function ($v) {
            $v->user = WxUser::where('id', $v->user_id)->first(['user_avatar', 'id', 'user_name']);
            $v->datetime = format_datetime($v->created_at);
        });

        return $this->success($data);
    }

}
